import axios from 'axios'
import Vue from 'vue'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken,
  removeToken
} from '@/utils/auth'
import baseURL from './baseUrl.js'
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: baseURL,
  withCredentials: false, // send cookies when cross-domain requests 跨域请求时发送cookies
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  },
  // timeout: 10000 // request timeout
})

let errorInfo = []
let websocket = null;
if (websocket == null || websocket.readyState != 1) {
  websocket = new WebSocket("ws://39.108.61.54:20000/monitor")
  // websocket = new WebSocket("ws://localhost:20000/monitor")
}

let userInfo = window.localStorage.getItem("userInfo");
let appInfo = window.navigator.userAgent;
let platform = window.navigator.platform;
let vm = new Vue({
  data: {
    errorInfo: [],
    onlineInfo: []
  }
})

vm.$watch('errorInfo', function() {
  if (userInfo != null) {

    if (websocket == null || websocket.readyState != 1) {
      websocket = new WebSocket("ws://39.108.61.54:20000/monitor")
      // websocket = new WebSocket("ws://localhost:20000/monitor")

    } else {
      if (websocket.readyState == 1) {

        if (vm.$data.errorInfo.length > 0) {
          let cerrorInfo = vm.$data.errorInfo.shift().replace("&nbsp;&nbsp;", ",")
          websocket.send("错误:" + cerrorInfo)
        }
      }
    }
  }
})

vm.$watch('onlineInfo', function() {
  if (userInfo != null) {

    if (websocket == null || websocket.readyState != 1) {
      websocket = new WebSocket("ws://39.108.61.54:20000/monitor")
      // websocket = new WebSocket("ws://localhost:20000/monitor")
    } else {
      if (websocket.readyState == 1) {

        if (vm.$data.onlineInfo.length % 10 == 1) {
          websocket.send("在线:" + userInfo.replace("&nbsp;&nbsp;", ","))
          vm.$data.onlineInfo = []
        }
      } else {
        if (vm.$data.onlineInfo.length % 10000 == 1) {
          vm.$data.onlineInfo = []
        }
      }
    }
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }

    vm.$data.onlineInfo.push(true)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    vm.$data.errorInfo.push(userInfo + "request错误" + error)
    return Promise.reject(error)
  }
)
// 多个合并一个
let tokenReset = true
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (response.data.type == 'application/octet-stream') {
      return response
    }
    const res = response.data
    if (res.code !== 200) {
      vm.$data.errorInfo.push(userInfo +
        "response错误 请求地址:" + response.config.url +
        "请求参数:" + response.config.data +
        "引用页面:" + window.location.href +
        "浏览器信息:" + appInfo +
        "平台:" + platform)
      if (res.code == -100) {
        res.data = []
        res.message = '登陆过期，请重新登录'
        if (tokenReset) {
          tokenReset = false
          MessageBox.confirm('您将要注销，可以取消以停留在此页面，或重新登录', '登陆过期，请重新登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
              // window.open(window.location.origin+'/#/login', '_blank');
            })
          }).catch(() => {
            // 取消不做处理
          })
        }
      } else if (res.code == 400) {
        // res.message = '禁止访问'
        Message({
          message: '禁止访问！',
          type: 'warning',
        })
      } else {
        return res
      }
    } else {
      let currentBodyData = res.data.dataBody
      let currentHeaderData = res.data.dataHeader
      let convertedResult = []
      if (currentBodyData && currentBodyData.length > 0) {
        currentBodyData.forEach(row => {
          let cobj = {}
          for (let i = 0; i < currentHeaderData.length; i++) {
            cobj[currentHeaderData[i]] = row[i]
          }
          convertedResult.push(cobj)
        })
        res.data = convertedResult
      } else if (currentBodyData && currentBodyData.length == 0) {
        res.data = convertedResult
      }
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    vm.$data.errorInfo.push(userInfo + "response错误" + error);
    // Message({
    //   message: '操作错误！',
    //   type: 'error',
    // })
    // removeToken()
    return Promise.reject(error)
  }
)

// 监听控制台报错
Vue.config.errorHandler = (err, vm, info) => {
  let { message, name } = err
  let context = "错误路径：" + window.location.href + ";" +
    "代码位置：" + info + ";" +
    "错误信息：" + message + ";" +
    "错误详情：" + err + "。";
  vm.$data.errorInfo.push(userInfo + "控制台错误" + context);
}

export default service
